package com.example.controller;

import com.example.entity.LoginResponse;
import com.example.entity.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.RedisCache;
import com.example.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 获取个人基本信息
     * @return 个人信息
     */
    @GetMapping
    public Result<LoginResponse> getUserInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        LoginResponse loginResponse = userService.findUserInfo(id);
        return Result.success(loginResponse);
    }

    /**
     * 用户修改密码
     * @param params 密码参数
     * @param token jwt令牌
     * @return 200 修改成功; 400 修改失败
     */
    @PatchMapping("/password")
    public Result updatePassword(@RequestBody Map<String, String> params, @RequestHeader("token") String token) {
        //1. 校验参数
        String oldPwd = params.get("oldPwd");
        String newPwd = params.get("newPwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd)) {
            return Result.error("缺少必要参数");
        }

        //原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        String msg = userService.identifyPassword(id, oldPwd);

        //2. 调用service完成密码更新
        userService.updatePassword(id, newPwd);

        //删除redis中对应的token
        redisCache.deleteObject(token);

        return Result.success(msg);
    }

    @PutMapping
    public Result<Object> updateUserInfo(@RequestBody User user){
        log.info("用户id{}",user);
        userService.updateUserInfo(user);
        return Result.success();
    }

    @PatchMapping("/profile")
    public Result<Object> updateUserProfile(@RequestBody Map<String, Object> request){
        String profile = (String) request.get("profile");
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userService.updateProfile(profile, id);
        return Result.success();
    }

}